package dictionary

import (
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/util"
	"strings"
	"time"
)

const (
	ENABLED  = 1
	DISABLED = 0
)

// 数据字典
type DictionarySet struct {
	Id        int64     `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	CreatedTs time.Time `json:"create_time"`
	Isused    int       `json:"isused"` //1 在用 ，0 停用
	Remarks   string    `json:"remarks"`
}

// 数据字典详细
type DictionaryDetail struct {
	Id        int64     `json:"id"`
	Key       string    `json:"key"`
	Value     string    `json:"value"`
	CreatedTs time.Time `json:"create_time"`
	Isused    int       `json:"isused"`
	Remarks   string    `json:"remarks"`
	DictId    int       `json:"dict_id"`
}

// 数据字典详细 - 返回拼接
type DictionaryDetailJson struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

// 数据字典详细 - 返回拼接
type DictionaryInfo struct {
	Name        string                 `json:"name"`
	Type        string                 `json:"type"`
	DictDetails []DictionaryDetailJson `json:"dictdetails"`
}

// 数据字典详细
type DictionaryInfoDb struct {
	Name  string `json:"name"`
	Type  string `json:"type"`
	Key   string `json:"key"`
	Value string `json:"value"`
}

// 获取字典所有信息
func GetDictInfo() ([]DictionaryInfo, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()

	dictInfosDb := []DictionaryInfoDb{}
	if err := sessionInstance.Table("dictionary_set").
		Join("inner", "dictionary_detail", "dictionary_set.id=dictionary_detail.dict_id").
		Cols("name", "type", "dictionary_set.isused", "key", "value", "dictionary_detail.isused").
		Where("dictionary_set.isused = 1 AND dictionary_detail.isused = 1").
		Find(&dictInfosDb); err != nil {
		return nil, err
	}
	//组装json
	dictInfos := []DictionaryInfo{}

	currType := ""
	tempDictInfo := DictionaryInfo{} //一个独立的字典

	for _, item := range dictInfosDb {
		if currType == item.Type {
			continue
		}
		currType = item.Type

		tempDictInfo = DictionaryInfo{} //一个独立的字典(clear)
		tempDictInfo.DictDetails = []DictionaryDetailJson{}
		tempDetailJsons := []DictionaryDetailJson{} //一条字典详情
		tempDetailJson := DictionaryDetailJson{}    //一条字典详情

		tempDictInfo.Type = item.Type
		tempDictInfo.Name = item.Name
		//组装所有子集
		for _, _item := range dictInfosDb {
			if currType == _item.Type {
				tempDetailJson.Key = _item.Key
				tempDetailJson.Value = _item.Value
				tempDetailJsons = append(tempDetailJsons, tempDetailJson)
			}
		}
		tempDictInfo.DictDetails = tempDetailJsons
		dictInfos = append(dictInfos, tempDictInfo)
	}
	return dictInfos, nil
}

// 获取字典列表
func GetDictList(dictName, dictType string, useStatus, pagesize, page int) (int, []*DictionarySet, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	dictName = strings.TrimSpace(dictName)
	dictType = strings.TrimSpace(dictType)
	offset := (page - 1) * pagesize
	if dictName != "" {
		sessionInstance = sessionInstance.Where("name like ?", "%"+dictName+"%")
	}
	if dictType != "" {
		sessionInstance = sessionInstance.And("type like ?", "%"+dictType+"%")
	}
	if useStatus == ENABLED || useStatus == DISABLED {
		sessionInstance = sessionInstance.And("isused=?", useStatus)
	}
	dictSet := []*DictionarySet{}
	count, err := sessionInstance.Limit(pagesize, offset).FindAndCount(&dictSet)
	if err != nil {
		return 0, nil, err
	}
	return int(count), dictSet, nil
}

// 新增字典
func insertDict(dict *DictionarySet) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Insert(dict); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 更新字典
func updateDict(dict *DictionarySet) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id=?", dict.Id).Cols("name", "type", "created_ts", "isused", "remarks").Update(dict); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 新增or更新字典
func SetDict(dict *DictionarySet) error {
	if dict.Id != 0 {
		return updateDict(dict)
	} else {
		dict.Id = util.GenSnowflakeInt64()
		return insertDict(dict)
	}
}

// 删除字典
func DelDict(id int64) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("dict_id=?", id).Delete(new(DictionaryDetail)); err != nil {
		sessionInstance.Rollback()
		return err
	}
	if _, err := sessionInstance.Where("id=?", id).Delete(new(DictionarySet)); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 重置字典状态
func SetDictStatus(id int64, status int) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	dict := DictionarySet{
		Isused: status,
	}
	sessionInstance.Begin()
	_, err := sessionInstance.Where("id=?", id).Cols("isused").Update(&dict)
	if err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 获取字典详细
func GetDictDetailList(dictId int64) ([]*DictionaryDetail, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()

	dictDetail := []*DictionaryDetail{}
	err := sessionInstance.Where("dict_id=?", dictId).Find(&dictDetail)

	if err != nil {
		return nil, err
	}
	return dictDetail, nil
}

// 获取字典详细
func GetDictDetailListByName(dictName string) ([]DictionaryInfoDb, error) {
	sessionInstance := db.Session()
	defer sessionInstance.Close()

	dictInfosDb := []DictionaryInfoDb{}
	if err := sessionInstance.Table("dictionary_set").
		Join("inner", "dictionary_detail", "dictionary_set.id=dictionary_detail.dict_id").
		Cols("name", "type", "dictionary_set.isused", "key", "value", "dictionary_detail.isused").
		Where("dictionary_set.isused = 1 AND dictionary_detail.isused = 1 AND dictionary_set.name like ?", "%"+dictName+"%").
		Find(&dictInfosDb); err != nil {
		return nil, err
	}
	return dictInfosDb, nil
}

// 新增字典详情
func insertDictDetail(dictDetail *DictionaryDetail) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Insert(dictDetail); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 更新字典
func updateDictDetail(dictDetail *DictionaryDetail) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id=?", dictDetail.Id).Cols("key", "value", "created_ts", "isused", "remarks", "dict_id").Update(dictDetail); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 新增or更新字典
func SetDictDetail(dictDetail *DictionaryDetail) error {
	if dictDetail.Id != 0 {
		return updateDictDetail(dictDetail)
	} else {
		dictDetail.Id = util.GenSnowflakeInt64()
		return insertDictDetail(dictDetail)
	}
}

// 删除字典详情
func DelDictDetail(id int64) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	sessionInstance.Begin()
	if _, err := sessionInstance.Where("id=?", id).Delete(new(DictionaryDetail)); err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}

// 重置字典详情状态
func SetDictDetailStatus(id int64, status int) error {
	sessionInstance := db.Session()
	defer sessionInstance.Close()
	dictDetail := DictionaryDetail{
		Isused: status,
	}
	sessionInstance.Begin()
	_, err := sessionInstance.Where("id=?", id).Cols("isused").Update(&dictDetail)
	if err != nil {
		sessionInstance.Rollback()
		return err
	}
	sessionInstance.Commit()
	return nil
}
